// 对话历史管理
import { config } from '../../config';
import { ChatStorage } from './storage'

type Message = {
  role: 'user' | 'assistant';
  content: string;
};

export class ChatHistory {
  private storage = new ChatStorage(); // 持久化工具
  private messages: Message[] = [];
  private readonly maxHistory: number;

  constructor() {
    this.maxHistory = config.MAX_HISTORY || 1000;
  }

  // 初始历史会话方法：是否从最后的会话回复对话历史
  async initialize(loadHistory: boolean): Promise<void> {
    if (loadHistory) {
      const history = await this.storage.loadLatestSession();
      this.messages = history;
    } else {
      await this.storage.clearCurrentSession();
      this.messages = [];
    }
  }

  async add(message: Message): Promise<void> {
    this.messages.push(message);
    this.trimHistory();
    await this.storage.saveHistory(this.messages); // 将信息写回文件
  }

  getMessages(): Message[] {
    return [...this.messages];
  }

  private trimHistory(): void {
    if (this.messages.length > this.maxHistory * 2) {
      this.messages = this.messages.slice(-this.maxHistory * 2);
    }
  }

  clear(): void {
    this.messages = [];
  }
}
